import { Game } from "../Game"
import GameConfig from "../GameConfig"
import { SquareGroup } from "../SquareGroup"
import { GameStatus, GameViewer } from "../types"
import pageConfig from "./PageConfig"
import { SquarePageView } from "./SquarePageView"
import $ from "jquery"

export class GamePageViewer implements GameViewer {
    private nextDom = $(".next")
    private panelDom = $(".panel")
    private scoreDom = $(".score")
    private tishiDom = $(".tishi")
    switch(curTeris: SquareGroup): void {
        curTeris.squares.forEach((sq) => {
            sq.viewer!.remove()
            sq.viewer = new SquarePageView(sq, this.panelDom)
        })
    }
    showNext(teris: SquareGroup): void {
        teris.squares.forEach((sq) => {
            sq.viewer = new SquarePageView(sq, this.nextDom)
        })
    }
    init(game: Game): void {
        // 1.设置区域宽高 -> 用代码渲染html
        this.panelDom.css({
            width: GameConfig.panelSize.width * pageConfig.width,
            height: GameConfig.panelSize.height * pageConfig.height
        })
        this.nextDom.css({
            width: GameConfig.nextSize.width * pageConfig.width,
            height: GameConfig.nextSize.height * pageConfig.height
        })
        // 2.注册键盘事件
        $(document).on("keydown", function (e) {
            if (e.key === "ArrowDown") {
                game.control_rotate()
            } else if (e.key === "ArrowUp") {
                game.control_rotate()
            } else if (e.key === "ArrowLeft") {
                game.control_left()
            } else if (e.key === "ArrowRight") {
                game.control_right()
            } else if (e.key === " ") {
                game.control_down()
            } else if (e.key === "Enter") {
                if (game.gameStatus === GameStatus.playing) {
                    game.pause()
                } else {
                    game.start()
                }
            }
        })
    }
    showScore(score: number): void {
        this.scoreDom.html(`分数：${score.toLocaleString()}`)
    }
    onGameStart(): void {
        this.tishiDom.html("")
        this.tishiDom.css({
            color: "red"
        })
    }
    onGamePause(): void {
        this.tishiDom.html("游戏暂停")
    }
    onGameOver(): void {
        this.tishiDom.html("游戏结束")
        this.tishiDom.css({
            color: "green"
        })
    }
}
